const fs = require('fs')
const JSONC = require('jsonc-parser')

function readFile(path){
    return fs.readFileSync(path, 'utf8')
}

function loadConfig(){
    const cwd = process.cwd()

    const confPath = cwd+'/easyisapi.conf'
    let config={}
    if (fs.existsSync(confPath)) {
        console.log('从当前路径加载easyisapi.conf',confPath)
        const configStr = readFile(confPath)
        //config = new Function('return '+configStr)()
        //config = JSON.parse(configStr);
        config = JSONC.parse(configStr)

    }

    if(process.env.EASYISAPI_CONF){
        if (fs.existsSync(process.env.EASYISAPI_CONF)) {
            console.log('从环境变量加载easyisapi.conf',process.env.EASYISAPI_CONF)
            let configStr = readFile(process.env.EASYISAPI_CONF)
            const configFromEnv = JSONC.parse(configStr)
            
            Object.assign(config,configFromEnv)
        }
    }
    if(global.__openapi_token){
        config.accessToken = global.__openapi_token
    }
    if(global.__openapi_url){
        config.url = global.__openapi_url
    }

    return config
}

const EasyisOpenApiClient = require('./EasyisOpenApiClient.js')


const DataService = require('./form/DataService.js')

module.exports = class EasyisOpenApi{
	constructor(config){// url accessKey accessSecret
        /* console.log('accessKey',accessKey)
        console.log('accessSecret',accessSecret) */
        this.client = new EasyisOpenApiClient(config)

        this.dataService = new DataService(this.client.request)
        

    }

    //static defaultEasyisOpenApi
    //static defaultEasyisOpenApiConf

    //每次创建一个新的 不要缓存
    static getInstance(){
        const config = loadConfig()

        /* let api
        const url = global.__openapi_url || config.url
        console.log('openapi url:',url) */
        //从System.property中获取
        /* const accessToken = global.__openapi_token || config.accessToken
        const accessKey = config.accessKey;
        const accessSecret = config.accessSecret;
        const camleNameModel = config.camleNameModel */
        const api = new EasyisOpenApi(config)//{url,accessKey,accessSecret,accessToken,camleNameModel}

		return api
    }

}


